import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Card, Row, Col, Button, Modal, Input, InputNumber } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';

import MyTree from '../../components/_public/MyTree';

import styles from './OutExam.less';
import EditTable from '../../components/_public/EditTable';
import TableModal from '../../components/_public/TableModal';

import { getParamUrl, minHeight, myMessage } from '../../utils/formatDataSource';

@connect(({ lesson3, question3, loading }) => ({
  lesson:lesson3,
  question:question3,
  treeLoading: loading.effects['lesson3/kjConfig'],
}))
class OutExam extends PureComponent {
  state = {
    currentAdd: 1, // 当前添加的题目类型  1 填空  2 选择  3 简答
    visible: false,
    addBtnDisabled: true,
    scoreModal: false,
    currentScoreType: 1,
    totalScore: 0,
    totalScoreXz: 0,
    totalScoreTk: 0,
    totalScoreJd: 0,
    examTime: 90,
    treeKeys: [],
    totalTreeKeys: [],
    questionTypeIds: [], // 选中的所有题型ID
    tk_data: [],
    xz_data: [],
    jd_data: [],
    selectedRowKeys: [],
    lessonId: '',
  };

  componentDidMount() {
    const { dispatch, location: { search } } = this.props;
    dispatch({
      type: 'lesson3/kjConfig',
    });
    const params = getParamUrl(search);
    const { lessonId, type } = params;
    this.setState({ lessonId });
    if (type !== undefined) {
      dispatch({
        type: 'question3/getHistory',
        payload: {
          lessonId: params.lessonId,
          type: 2,
        },
      }).then(() => {
        const { examHistory } = this.props.question;

        const { selectedRowKeys } = this.state;

        const {
          tk_data,
          xz_data,
          jd_data,
          totalScore,
          examTime,
          treeKeys,
          totalTreeKeys,
        } = examHistory;

        const existTK = selectedRowKeys.find(s => s.type === 2);

        const existXZ = selectedRowKeys.find(s => s.type === 1);

        const existJD = selectedRowKeys.find(s => s.type === 3);

        this.getHistoryRows(selectedRowKeys, existTK, tk_data, 2);

        this.getHistoryRows(selectedRowKeys, existXZ, xz_data, 1);

        this.getHistoryRows(selectedRowKeys, existJD, jd_data, 3);

        const disabled = treeKeys.length === 0 ? true : false;

        const questionTypeIds = treeKeys
          .filter(t => {
            const arr = t.split('_');
            if (arr.length === 5) {
              return true;
            } else {
              return false;
            }
          })
          .map(t => {
            const arr = t.split('_');
            return arr[arr.length - 1];
          });

        this.setState({
          tk_data,
          xz_data,
          jd_data,
          selectedRowKeys,
          totalScore,
          examTime,
          treeKeys,
          totalTreeKeys,
          addBtnDisabled: disabled,
          questionTypeIds,
        });
      });
    }

    dispatch({
      type: 'question3/homeworkInfo',
      payload: {
        lessonId,
        type: 3,
      },
    });
  }

  getHistoryRows = (selectedRowKeys, exist, data, type) => {
    if (exist !== undefined) {
      data.map(t => {
        let e = exist.data.find(d => d.id === t.id);
        if (e === undefined) {
          exist.data.push(t.id);
        }
      });
    } else {
      const temp = {
        type: type,
        data: [],
      };
      data.map(t => temp.data.push(t.id));

      selectedRowKeys.push(temp);
    }
  };

  /**
   * 递归获取当前知识树中所有被选中的题型ID
   * @param data
   * @param keys
   * @param questionTypeIds
   * @private
   */
  _m_m1 = (data, keys, questionTypeIds) => {
    data.map(d => {
      if (d.sons) {
        this._m_m1(d.sons, keys, questionTypeIds);
      }
      if (d.type === 5) {
        keys.map(k => {
          if (k === d.uniqueKey) {
            questionTypeIds.push(d.id);
          }
        });
      }
    });
  };

  _m_m2 = data => {
    const { currentAdd, tk_data, xz_data, jd_data } = this.state;

    switch (currentAdd) {
      case 2:
        tk_data.push(...data);
        this.setState({ tk_data });
        break;
      case 1:
        xz_data.push(...data);
        this.setState({ xz_data });
        break;
      case 3:
        jd_data.push(...data);
        this.setState({ jd_data });
        break;
      default:
        console.log('这不是一个有效的题目类型');
    }
  };

  _m1 = (checkedKeys, totalKeys) => {
    const { treeList } = this.props.lesson;
    let questionTypeIds = [];
    let addBtnDisabled = true;

    this._m_m1(treeList, totalKeys, questionTypeIds);

    if (questionTypeIds.length !== 0) {
      addBtnDisabled = false;
    }
    this.setState({
      treeKeys: checkedKeys,
      totalTreeKeys: totalKeys,
      questionTypeIds,
      addBtnDisabled,
    });
  };

  _m2 = e => {
    this.setState({ visible: e });
  };
  _m3 = e => {
    console.log(e);
    const data = e.map(item => {
      return { ...item, score: '请设置分数' };
    });
    this._m_m2(data);
  };
  _m4 = id => {
    let { selectedRowKeys, tk_data, xz_data, jd_data } = this.state;

    selectedRowKeys.map(s => {
      s.data = s.data.filter(d => d !== id);
    });

    tk_data = tk_data.filter(t => t.id !== id);
    xz_data = xz_data.filter(t => t.id !== id);
    jd_data = jd_data.filter(t => t.id !== id);

    const totalScore = this.getTotalScore(xz_data, tk_data, jd_data);

    this.setState({
      selectedRowKeys: [...selectedRowKeys],
      tk_data,
      xz_data,
      jd_data,
      totalScore,
    });
  };
  _m5 = (id, score) => {
    let { tk_data, xz_data, jd_data } = this.state;

    tk_data.map(t => {
      if (t.id === id) {
        t.score = score;
      }
    });
    xz_data.map(t => {
      if (t.id === id) {
        t.score = score;
      }
    });
    jd_data.map(t => {
      if (t.id === id) {
        t.score = score;
      }
    });

    const totalScore = this.getTotalScore(xz_data, tk_data, jd_data);

    this.setState({
      tk_data: [...tk_data],
      xz_data: [...xz_data],
      jd_data: [...jd_data],
      totalScore,
    });
  };
  _m6 = type => {
    const { dispatch } = this.props;
    const { questionTypeIds, selectedRowKeys } = this.state;

    const exist = selectedRowKeys.find(s => s.type === type);
    if (exist) {
      exist.data = [];
      exist.page = 1;
    } else {
      selectedRowKeys.push({
        type,
        data: [],
        page: 1,
      });
    }

    dispatch({
      type: 'lesson3/questionList',
      payload: {
        questiontypeId: questionTypeIds.join(','),
        type: type,
        existIdStr: this.getCurrentExistIds(type),
      },
    });
    this.setState({
      visible: true,
      currentAdd: type,
      selectedRowKeys: [...selectedRowKeys],
    });
  };
  _m7 = (page, pageSize, diqu, nianfen, laiyuan, tixing, sftj, hard, ckcd, nianji, sfhjx, tihao, use) => {
    const { dispatch } = this.props;

    const { questionTypeIds, selectedRowKeys, currentAdd } = this.state;

    const current = selectedRowKeys.find(s => s.type === currentAdd);
    current.page = page;

    let params = {};
    if (diqu !== '-1') {
      params.diqu = diqu;
    }
    if (nianfen !== '-1') {
      params.nianfen = nianfen;
    }
    if (laiyuan !== '-1') {
      params.laiyuan = laiyuan;
    }
    if (tixing !== '-1') {
      params.tixing = tixing;
    }
    if (sftj !== '-1') {
      params.sftj = sftj;
    }
    if (hard !== '-1') {
      params.hard = hard;
    }
    if (ckcd !== '-1') {
      params.ckcd = ckcd;
    }
    if (nianji !== '-1') {
      params.nianji = nianji;
    }
    if (sfhjx !== '-1') {
      params.sfhjx = sfhjx;
    }
    if (tihao !== '-1') {
      params.tihao = tihao;
    }
    if (use !== '-1') {
      params.use = use;
    }

    dispatch({
      type: 'lesson3/questionList',
      payload: {
        page,
        pageSize,
        questiontypeId: questionTypeIds.join(','),
        type: this.state.currentAdd,
        existIdStr: this.getCurrentExistIds(),
        ...params,
      },
    });
  };

  _m7Old = (page, pageSize, hard, use) => {
    const { dispatch } = this.props;

    const { questionTypeIds, selectedRowKeys, currentAdd } = this.state;

    const current = selectedRowKeys.find(s => s.type === currentAdd);
    current.page = page;

    let params = {};
    if (hard !== '-1') {
      params.hard = hard;
    }
    if (use !== '-1') {
      params.use = use;
    }

    dispatch({
      type: 'lesson3/questionList',
      payload: {
        page,
        pageSize,
        questiontypeId: questionTypeIds.join(','),
        type: this.state.currentAdd,
        existIdStr: this.getCurrentExistIds(),
        ...params,
      },
    });
  };

  _m8 = () => {
    let selectedData = [];
    const { tk_data, xz_data, jd_data, treeKeys, totalTreeKeys, totalScore } = this.state;
    selectedData = [...tk_data, ...xz_data, ...jd_data];
    const { dispatch, question: { lessonId } } = this.props;

    if (selectedData.length === 0) {
      myMessage.error('请先添加题目', 2);
      return;
    }

    const error = selectedData.filter(s => s.score === '请设置分数');
    if (error.length > 0) {
      myMessage.error('请设置分数', 2);
      return;
    }

    const selectedTrees = treeKeys.join(',');

    const totalTrees = totalTreeKeys.join(',');

    dispatch({
      type: 'question3/saveList',
      payload: {
        questionList: selectedData,
        lessonId,
        type: 2,
        time: this.state.examTime,
        selectedTrees,
        totalTrees,
        totalScore,
      },
    });
  };

  handleRowChange = rows => {
    const { selectedRowKeys, currentAdd } = this.state;

    const exist = selectedRowKeys.find(s => s.type === currentAdd);

    exist.data = rows;
  };

  scoreOk = () => {
    const { totalScoreXz, totalScoreTk, totalScoreJd, xz_data, tk_data, jd_data } = this.state;
    xz_data.map(x => {
      x.score = totalScoreXz;
    });
    tk_data.map(x => {
      x.score = totalScoreTk;
    });
    jd_data.map(x => {
      x.score = totalScoreJd;
    });

    const totalScore = this.getTotalScore(xz_data, tk_data, jd_data);

    this.setState({
      tk_data: [...tk_data],
      xz_data: [...xz_data],
      jd_data: [...jd_data],
      scoreModal: false,
      totalScore,
    });
  };

  scoreCancel = () => {
    this.setState({ scoreModal: false });
  };

  setScore = type => {
    this.setState({
      currentScoreType: type,
      scoreModal: true,
    });
  };

  getScoreInput = () => {
    const { currentScoreType } = this.state;

    switch (currentScoreType) {
      case 1:
        return this.state.totalScoreXz;
      case 2:
        return this.state.totalScoreTk;
      case 3:
        return this.state.totalScoreJd;
    }
  };
  scoreChange = value => {
    const { currentScoreType } = this.state;

    switch (currentScoreType) {
      case 1:
        this.setState({
          totalScoreXz: value.target.value,
        });
        break;
      case 2:
        this.setState({
          totalScoreTk: value.target.value,
        });
        break;
      case 3:
        this.setState({
          totalScoreJd: value.target.value,
        });
        break;
      default:
        console.log('2333');
    }
  };

  changeExamTime = e => {
    this.setState({
      examTime: e,
    });
  };

  getTotalScore = (tk_data, xz_data, jd_data) => {
    let totalScore = 0;
    tk_data.map(t => {
      if (t.score !== '请设置分数') {
        totalScore = totalScore + Number(t.score);
      }
    });
    xz_data.map(t => {
      if (t.score !== '请设置分数') {
        totalScore = totalScore + Number(t.score);
      }
    });
    jd_data.map(t => {
      if (t.score !== '请设置分数') {
        totalScore = totalScore + Number(t.score);
      }
    });

    return totalScore;
  };

  getQuestionList = (diqu, nianfen, laiyuan, tixing, sftj, hard, ckcd, nianji, sfhjx, tihao, use) => {
    const { dispatch } = this.props;

    const { questionTypeIds } = this.state;
    let params = {};
    if (diqu !== '-1') {
      params.diqu = diqu;
    }
    if (nianfen !== '-1') {
      params.nianfen = nianfen;
    }
    if (laiyuan !== '-1') {
      params.laiyuan = laiyuan;
    }
    if (tixing !== '-1') {
      params.tixing = tixing;
    }
    if (sftj !== '-1') {
      params.sftj = sftj;
    }
    if (hard !== '-1') {
      params.hard = hard;
    }
    if (ckcd !== '-1') {
      params.ckcd = ckcd;
    }
    if (nianji !== '-1') {
      params.nianji = nianji;
    }
    if (sfhjx !== '-1') {
      params.sfhjx = sfhjx;
    }
    if (tihao !== '-1') {
      params.tihao = tihao;
    }
    if (use !== '-1') {
      params.use = use;
    }
    dispatch({
      type: 'lesson3/questionList',
      payload: {
        questiontypeId: questionTypeIds.join(','),
        type: this.state.currentAdd,
        existIdStr: this.getCurrentExistIds(),
        ...params,
      },
    });
  };

  getCurrentExistIds = type => {
    const { currentAdd, xz_data, tk_data, jd_data } = this.state;
    const arr = [];
    const existId = type !== undefined ? type : currentAdd;
    switch (existId) {
      case 1:
        xz_data.map(x => arr.push(x.id));
        break;
      case 2:
        tk_data.map(x => arr.push(x.id));
        break;
      case 3:
        jd_data.map(x => arr.push(x.id));
        break;
      default:
    }
    return arr.join(',');
  };

  render() {
    const { treeList = [] } = this.props.lesson;

    const { homeworkInfo = {} } = this.props.question;

    const { visible, selectedRowKeys, currentAdd, tk_data, xz_data, jd_data } = this.state;

    const exist = selectedRowKeys.filter(s => s.type === currentAdd);

    const data =
      exist.length === 0
        ? {
            data: [],
            page: 1,
          }
        : exist[0];

    return (
      <PageHeaderLayout>
        <Col span={9}>
          <Card style={{ minHeight: minHeight }}>
            <MyTree
              dataSource={treeList}
              checkedKeys={this.state.treeKeys}
              handleCheck={this._m1}
              loading={this.props.treeLoading}
            />
          </Card>
        </Col>
        <Col span={15}>
          <Card style={{ marginBottom: '10px', textAlign: 'right' }}>
            <Button
              type="primary"
              size="small"
              onClick={() =>
                this.props.dispatch(
                  routerRedux.push(`/lesson/3/lesson-info?lessonId=${this.state.lessonId}`)
                )
              }
            >
              返回
            </Button>
          </Card>
          <Card bordered={false}>
            <Row>
              <Col span={7}>
                上课时间：<strong>{homeworkInfo.formatDateStr}</strong>
              </Col>
              <Col span={4}>
                上课状态：<strong>{homeworkInfo.lessonStatus}</strong>
              </Col>
              <Col span={4}>
                备课状态：<strong>{homeworkInfo.bkStatus}</strong>
              </Col>
              <Col span={4}>
                评价状态：<strong>无</strong>
              </Col>
              <Col span={5}>出题学生：{homeworkInfo.students}</Col>
            </Row>
          </Card>
          <Card
            bordered={false}
            title="选择题"
            className={styles.Card}
            extra={
              <a href="javascript:;" onClick={() => this.setScore(1)}>
                批量设置分数
              </a>
            }
          >
            <EditTable onDelete={this._m4} onCellChange={this._m5} data={xz_data} />
            <Button
              style={{ marginTop: 10 }}
              onClick={() => this._m6(1)}
              type="primary"
              disabled={this.state.addBtnDisabled}
            >
              添加
            </Button>
          </Card>
          <Card
            bordered={false}
            title="填空题"
            className={styles.Card}
            extra={
              <a href="javascript:;" onClick={() => this.setScore(2)}>
                批量设置分数
              </a>
            }
          >
            <EditTable onDelete={this._m4} onCellChange={this._m5} data={tk_data} />
            <Button
              style={{ marginTop: 10 }}
              onClick={() => this._m6(2)}
              type="primary"
              disabled={this.state.addBtnDisabled}
            >
              添加
            </Button>
          </Card>
          <Card
            bordered={false}
            title="简答题"
            className={styles.Card}
            extra={
              <a href="javascript:;" onClick={() => this.setScore(3)}>
                批量设置分数
              </a>
            }
          >
            <EditTable onDelete={this._m4} onCellChange={this._m5} data={jd_data} />
            <Button
              style={{ marginTop: 10 }}
              onClick={() => this._m6(3)}
              type="primary"
              disabled={this.state.addBtnDisabled}
            >
              添加
            </Button>
          </Card>
          <TableModal
            visible={visible}
            onClickModal={this._m2}
            onClickSubmit={this._m3}
            dataSource={this.props.lesson.questionListInfo}
            getPageData={this._m7}
            defaultRows={data}
            defaultRowChange={this.handleRowChange}
            getQuestionList={this.getQuestionList}
          />

          <Card bordered={false}>
            <Row type="flex" align="middle">
              <Col span={2}> 考试时间：</Col>
              <Col span={3}>
                {' '}
                <InputNumber
                  value={this.state.examTime}
                  onChange={this.changeExamTime}
                  min={1}
                  max={1000}
                />
              </Col>
              <Col span={5}>考试分数：{this.state.totalScore}分</Col>
              <Col span={14} style={{ textAlign: 'right' }}>
                <Button type="primary" onClick={this._m8}>
                  保存
                </Button>&nbsp;&nbsp;
              </Col>
            </Row>
          </Card>
        </Col>

        <Modal
          visible={this.state.scoreModal}
          title="请设置分数"
          width="15%"
          onOk={this.scoreOk}
          onCancel={this.scoreCancel}
        >
          <Input value={this.getScoreInput()} onChange={this.scoreChange} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}

export default OutExam;
